package com.itheima.reggie.interceptor;

import com.alibaba.fastjson.JSON;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.reggie.common.EmployeeHolder;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.plaf.synth.SynthOptionPaneUI;

//登录拦截器
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1、判断登录状态，如果已登录，则直接放行
        Employee employee = (Employee) request.getSession().getAttribute("SESSION_EMPLOYEE");
        if (employee == null) {
            //将employ方法ThreadLocal
            System.out.println("用户未登录");
            ResultInfo resultInfo = ResultInfo.error("NOTLOGIN");
            String json =new ObjectMapper().writeValueAsString(resultInfo);
            response.getWriter().write(json);
            return false;
        }
        else{
            EmployeeHolder.set(employee);

            return true;
        }

//        //2、如果未登录,禁止通行,返回错误
//        String json = JSON.toJSONString(ResultInfo.error("NOTLOGIN"));
//        response.getWriter().write(json);
//        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        EmployeeHolder.remove();
    }
}